package ys

import (
	"encoding/json"
	"errors"
	"gitee.com/injoyai/goutil/conv"
	"gitee.com/injoyai/goutil/g"
	"gitee.com/injoyai/goutil/net/http"
)

// GetAddr 获取视频地址列表
func GetAddr(appKey, secretKey string) ([]g.Map, error) {
	token, err := getToken(appKey, secretKey)
	if err != nil {
		return nil, err
	}
	return getAddr(token)
}

func getToken(appKey, secretKey string) (string, error) {
	resp := http.Url("https://open.ys7.com/api/lapp/token/get").FormField(g.Map{
		"appKey":    appKey,
		"appSecret": secretKey,
	}).Debug().Post()
	if err := resp.Err(); err != nil {
		return "", err
	}
	m := conv.NewMap(resp.GetBody())
	if m.GetInt("code") != 200 {
		return "", errors.New(m.GetString("msg", "获取失败"))
	}
	token := m.GetString("data.accessToken")
	return token, nil
}

func getDeviceList(token string) ([]g.Map, error) {
	resp := http.Url("https://open.ys7.com/api/lapp/device/list").FormField(g.Map{
		"accessToken": token,
	}).Debug().Post()
	if resp.Err() != nil {
		return nil, resp.Err()
	}
	m := conv.NewMap(resp.GetBody())
	if m.GetInt("code") != 200 {
		return nil, errors.New(m.GetString("msg", "获取失败"))
	}
	result := []g.Map{}
	err := json.Unmarshal(resp.GetBody(), &result)
	return result, err
}

func getAddr(token string) ([]g.Map, error) {
	resp := http.Url("https://open.ys7.com/api/lapp/live/video/list").FormField(g.Map{
		"accessToken": token,
	}).Debug().Post()
	if resp.Err() != nil {
		return nil, resp.Err()
	}
	m := conv.NewMap(resp.GetBody())
	if m.GetInt("code") != 200 {
		return nil, errors.New(m.GetString("msg", "获取失败"))
	}
	result := []g.Map{}
	err := json.Unmarshal(m.GetBytes("data"), &result)
	return result, err
}
